# send a file to email server


import os, sys
from stat import *

import smtplib, mimetypes
import email, mailbox
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

import GUIDFactory, getpass

class ESender:
    ''' one file sender '''
    def __init__(self, host, port = 25, attachmentSize = 1000000): #10000000
        ''' init esender '''
        print 'ESender : initializing\n'
        self.m_smtpClient = smtplib.SMTP_SSL(host, port);
        
        self.m_nAttachmentSize = attachmentSize;
        
    def __del__(self):
        print 'ESender : del\n'
        self.m_smtpClient.close();
    
    def Login(self, user, psw):
        ''' login server '''
        self.m_strUser = user;
        self.m_smtpClient.login(user, psw);
                
        
    def Send(self, to_addrs, fileFullPath):
        '''send file'''
        #create threads to send each attachments
        
        #open file 
        print 'open file  ' + fileFullPath + '\n'
        
        if os.path.isfile(fileFullPath) == False :
            print 'path does not point a file'
        file = open(fileFullPath, 'rb');
        
        dataBuffer = '';
        nPartIndex = 0;    #file part index
        nFileSize = os.stat(fileFullPath)[ST_SIZE];
        
        guidFactory = GUIDFactory.GUIDFactory();
        strSessionID = guidFactory.GetGuid();
        
        nEmailCount = nFileSize / self.m_nAttachmentSize;
        if nFileSize % self.m_nAttachmentSize != 0 :
            nEmailCount = nEmailCount + 1;
        
        for nPartIndex in range(1, nEmailCount + 1) :
            # fill buffer
            dataBuffer = file.read(self.m_nAttachmentSize);

            print 'create email\n'
            msg = MIMEMultipart();
            msg['Index'] = 'lhz';
            msg['Subject'] = "[eStore-lhz]" + strSessionID + "-" + "%d" % nPartIndex  #product name - author - sessionid - PartIndex
            msg['From'] = self.m_strUser;        #get from user setting
            msg['To'] = 'your email';          #get from user setting


            fileName = fileFullPath[ fileFullPath.rfind('\\') + 1 : ];
            # text
            txt = MIMEText("FileName:%s\n Part/Total: %d/%d" %(fileName, nPartIndex, nEmailCount), _charset='utf-8')
            msg.attach(txt);
            
            # attachment
            
            ctype,encoding = mimetypes.guess_type(fileFullPath)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype,subtype = ctype.split('/',1)
            attachment = MIMEBase(maintype,subtype)
            attachment.set_payload(dataBuffer);
            Encoders.encode_base64(attachment);
            attachment.add_header('Content-disposition','attachment', filename = fileName + ".est")
            msg.attach(attachment);
            
            
            #-------------------------------------------
            from_addr = email.Utils.formataddr(('luohongzhi', 'luohongzhi@gmail.com'))
            to_addr = email.Utils.formataddr(('luohongzhi', 'luohongzhi@gmail.com'))
            
            mbox = mailbox.mbox('example.mbox')
            mbox.lock()
            try:
                msg = mailbox.mboxMessage()
                msg.set_unixfrom('author Sat Feb  7 01:05:34 2009')
                msg['From'] = from_addr
                msg['To'] = to_addr
                msg['Subject'] = 'Sample message 1'
                msg.set_payload('This is the body.\nFrom (should be escaped).\nThere are 3 lines.\n')
                mbox.add(msg)
                mbox.flush()
                
                msg = mailbox.mboxMessage()
                msg.set_unixfrom('author')
                msg['From'] = from_addr
                msg['To'] = to_addr
                msg['Subject'] = 'Sample message 2'
                msg.set_payload('this is the second body.\n')
                mbox.add(msg)
                mbox.flush()
                
            finally:
                mbox.unlock()
                    
            
            
            # send mail
            print 'send email begin\n'
            self.m_smtpClient.sendmail(self.m_strUser, to_addrs, mbox);
            print 'send email end\n'
            
    
        
        file.close();


#end class
                

def es_raw_input(dispStr) :
    strInput = raw_input(dispStr)
    return strInput.strip('\r')
    

############################################################################
# self test function
# read these params 
if __name__ == '__main__':
    sender = ESender(es_raw_input('smtp server : ').strip('\r'), int(es_raw_input("port : "), 10), int(es_raw_input("attachment size : "), 10));
    sender.Login(es_raw_input("User : "), getpass.getpass())
    sender.Send(es_raw_input("send to : "), es_raw_input("input file full path : "));